package com.itheima.d6_synchronized_lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 目标：模拟线程安全问题。
 */
public class ThreadTest {
    public static void main(String[] args) {
        TheadPiao theadPiao = new TheadPiao();
        Thread t1 = new Thread(theadPiao, "窗口1");
        Thread t2 = new Thread(theadPiao, "窗口2");
        Thread t3 = new Thread(theadPiao, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class TheadPiao implements Runnable {
    private int count = 100;
    ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                reentrantLock.lock();
                if (count <= 0) {
                    break;
                } else {
                    count--;
                    System.out.println(Thread.currentThread().getName() + " 窗口，正在卖票 还剩 " + count + " 张票");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException(e);
            } finally {
                reentrantLock.unlock();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
